package com.zrt.pad.util;

import java.math.BigDecimal;
import java.util.Random;

import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Toast;

import com.chinaums.umsswipe.app.IUmsCancelOrderResultListener;
import com.chinaums.umsswipe.app.IUmsSwipeResultListener;
import com.chinaums.umsswipe.app.IUmsSwipeService;
import com.zrt.pad.commonui.SharedApplication;
import com.zrt.pad.commonui.task.UMSPrintTask;

public class UMS {
	public UMS() {
		bindUmsSwipService();
	}

	private Activity ac;
	private AsyncTask<Object, Object, Boolean> successTask;

	public void init(Activity ac, AsyncTask<Object, Object, Boolean> successTask) {
		this.ac = ac;
		this.successTask = successTask;
	}

	private IUmsSwipeService mUmsSwipeService;
	private static final String TAG = "CardPayTask";

	private ServiceConnection mConnection = new ServiceConnection() {

		@Override
		public void onServiceConnected(ComponentName className, IBinder service) {
			Log.e(TAG, "Service has connected");
			mUmsSwipeService = IUmsSwipeService.Stub.asInterface(service);
			synchronized (lock) {
				lock.notify();
			}
		}

		@Override
		public void onServiceDisconnected(ComponentName className) {
			Log.e(TAG, "Service has unexpectedly disconnected");
			mUmsSwipeService = null;
		}
	};

	private PayResultListener mPayResultListener = new PayResultListener();
	private CancelOrderResultListener mCancelOrderResultListener = new CancelOrderResultListener();

	private void bindUmsSwipService() {
		Log.i(TAG, "bindUmsSwipService");
		Intent intent = new Intent();
		intent.setClassName("com.chinaums.umsswipe.app",
				"com.chinaums.umsswipe.app.UmsSwipeService");
		SharedApplication.context.bindService(intent, mConnection,
				Context.BIND_AUTO_CREATE);
	}

	private void unbindUmsSwipService() {
		Log.i(TAG, "unbindUmsSwipService");
		SharedApplication.context.unbindService(mConnection);
	}

	private boolean rebindService() {
		ac.runOnUiThread(new Runnable() {

			@Override
			public void run() {
				new AlertDialog.Builder(ac).setTitle("提示").setMessage("支付服务正在初始�?...").setPositiveButton("确定", null).show();

			}
		});
		Log.e(TAG, "mUmsSwipeService is null.");
		unbindUmsSwipService();
		bindUmsSwipService();
		synchronized (lock) {
			try {
				lock.wait(3000);
			} catch (InterruptedException e) {

			}
		}
		if (mUmsSwipeService == null) {
			ac.runOnUiThread(new Runnable() {

				@Override
				public void run() {
					new AlertDialog.Builder(ac).setTitle("提示").setMessage("支付服务初始化失败！").setPositiveButton("确定", null).show();

				}
			});
			return false;
		} else {
			return true;
		}
	}

	class PayResultListener extends IUmsSwipeResultListener.Stub {

		@Override
		public void payResult(Bundle result) throws RemoteException {
			final String payResult = result.getString("pay_result");
			Log.i(TAG, "pay result " + payResult);
			if ("failed".equals(payResult)) {

			} else {
				if (successTask != null) {
					successTask.execute();
				}
				String swipInfo = result.getString("pay_resultInfo");
				try {
					swipInfo = new JSONObject(swipInfo).put("_orderId",
							merOrderId).toString();
				} catch (Exception e) {

				}
				new UMSPrintTask().execute(swipInfo);
			}
			ac.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					new AlertDialog.Builder(ac).setTitle("提示").setMessage("刷卡结果:" + payResult).setPositiveButton("确定", null).show();

				}
			});
			merOrderId = null;
		}
	}

	class CancelOrderResultListener extends IUmsCancelOrderResultListener.Stub {

		@Override
		public void cancelOrderResult(Bundle result) throws RemoteException {
			final String payResult = result.getString("pay_result");
			Log.i(TAG, "cancel result " + payResult);
			if ("failed".equals(payResult)) {

			} else {
				if (successTask != null) {
					successTask.execute();
				}
				String swipInfo = result.getString("pay_resultInfo");
				try {
					swipInfo = new JSONObject(swipInfo).put("_orderId",
							merOrderId).toString();
				} catch (Exception e) {

				}
				new UMSPrintTask().execute(swipInfo);
			}
			ac.runOnUiThread(new Runnable() {
				@Override
				public void run() {
					new AlertDialog.Builder(ac).setTitle("提示").setMessage("撤销结果:" + payResult).setPositiveButton("确定", null).show();

				}
			});
			merOrderId = null;
		}
	}

	private String merOrderId;

	public static String getRandomNumber(int length) {
		StringBuffer buffer = new StringBuffer(length);
		for (int i = 0; i < length; i++) {
			int temp = getRandom(0, 10);
			buffer.append(temp);
		}
		return buffer.toString();
	}

	// 获取随机数字
	public static final int getRandom(int min, int max) {
		Random ran = new Random();
		return min + ((ran.nextInt() >>> 1) % max);
	}

	public void settings(View v) {
		if (mUmsSwipeService == null) {
			rebindService();
			return;
		}
		try {
			mUmsSwipeService.startSettings();
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	public void cancelOrder(String orderId) {
		if (mUmsSwipeService == null) {
			if (rebindService() == false) {
				return;
			}
		}
		merOrderId = orderId;
		Bundle args = new Bundle();
		args.putString("acceptMID", "898000058120011");
		args.putString("merOrderId", orderId);
		args.putString("billsMID", "898000093990001");
		args.putString("operator", "001");
		try {
			mUmsSwipeService.cancelOrder(args, mCancelOrderResultListener);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}

	private Object lock = new Object();

	public void pay(BigDecimal payment, String saleNo) {
		pay(payment, "898000058120011", "898000093990001", saleNo);
	}

	public void pay(BigDecimal payment, String acceptMid, String billsMid, String orderId) {
		if (mUmsSwipeService == null) {
			if (rebindService() == false) {
				return;
			}
		}
		String amount = payment.multiply(new BigDecimal(100)).setScale(0)
				.toString();
		Bundle args = new Bundle();
		args.putString("acceptMID", acceptMid);
		args.putString("amount", amount);
		merOrderId = orderId;
		args.putString("merOrderId", merOrderId);
		args.putString("billsMID", billsMid);
		args.putString("operator", "001");
		try {
			mUmsSwipeService.payOrder(args, mPayResultListener);
		} catch (RemoteException e) {
			e.printStackTrace();
		}
	}
}
